package com.hds.modules.app.entity.wx.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.hds.modules.app.entity.wx.po.AccessToken;

import net.sf.json.JSONObject;

/**
 *
 * 发送https请求的通用工具类
 */
public class WeixinUtil
{
    //请求获取access_token的URL路径
    private static final String GET_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

    /**
     * 发送https请求
     *
     * @param requestUrl
     * @param requestMethod
     * @return
     */
    public static JSONObject sendHttpsRequest(String requestUrl,String requestMethod,String outputStr)
    {
        //存放结果数据的
        JSONObject result = null;

        //创建SSLContext对象，并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};

        //创建安全套接字的上下文
        SSLContext sslContext;

        try {
            //获取SSL示例
            sslContext = SSLContext.getInstance("SSL","SunJSSE");

            //初始化
            sslContext.init(null, tm, new SecureRandom());

            //从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            //建立连接
            URL url = new URL(requestUrl);

            //打开连接
            HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();

            //设置安全套接字工厂
            conn.setSSLSocketFactory(ssf);

            //设置是否允许输入与输出
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);

            //设置请求方式
            conn.setRequestMethod(requestMethod);

            //向输出流中输出参数
            if( null != outputStr)
            {
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            //从输入流中获取返回的内容
            InputStream inputStream = conn.getInputStream();

            //将字节流转换为字符流
            InputStreamReader reader = new InputStreamReader(inputStream);

            //带缓冲的字符流
            BufferedReader bufferedReader = new BufferedReader(reader);

            //开始读取数据
            String str = null;
            StringBuffer buffer = new StringBuffer();

            //循环读取一行数据
            while( (str = bufferedReader.readLine()) != null)
            {
                buffer.append(str);
            }

            //关闭流
            bufferedReader.close();
            reader.close();
            inputStream.close();
            inputStream = null;

            //断开连接
            conn.disconnect();

            //将json格式的字符串转换为json对象
            //{"access_token":"ACCESS_TOKEN","expires_in":7200}
            result = JSONObject.fromObject(buffer.toString());

        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  result;
    }

    /**
     * 获取access_token的方法
     * 返回 AccessToken对象
     *
     * @return
     */
    public static AccessToken getAccessToken(String appid,String appSecret)
    {
        AccessToken accessToken= null;

        //替换成真正要请求的路径
        String requestUrl = GET_ACCESS_TOKEN.replace("APPID", appid).replace("APPSECRET", appSecret);

        JSONObject result = sendHttpsRequest(requestUrl,"GET",null);

        if(null != result)
        {
            accessToken = new AccessToken();

            //从result对象中解析出 access_token和expires_in
            //{"access_token":"ACCESS_TOKEN","expires_in":7200}
            accessToken.setAccess_token(result.getString("access_token"));

            accessToken.setExpiers_in(result.getString("expires_in"));
        }

        return accessToken;
    }



    /**
     * 根据内容类型来判断返回文件的扩展名
     *
     * 2015.10.29
     *
     * @param contentType 内容类型
     * @return
     */
    public static String getFileExt(String contentType)
    {
        String fileExt = "";

        if ("image/jpeg".equals(contentType))
        {
            fileExt = ".jpg";
        }
        if ("image/gif".equals(contentType))
        {
            fileExt = ".gif";
        }
        else if ("audio/mpeg".equals(contentType))
        {
            fileExt = ".mp3";
        }
        else if ("audio/amr".equals(contentType))
        {
            fileExt = ".amr";
        }
        else if ("video/mp4".equals(contentType))
        {
            fileExt = ".mp4";
        }
        else if ("video/mpeg4".equals(contentType))
        {
            fileExt = ".mp4";
        }else
        {
            System.out.println("未知的类型..");
        }

        return fileExt;
    }


    /**
     * URL编码（utf-8）
     *
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}